import React from "react";
import { useState, useEffect } from 'react';
import { CRow, CCol, CFormSelect, CForm, CFormLabel, CFormInput, CButton, CTable, CTableBody, CTableDataCell, CTableHead, CTableHeaderCell, CTableRow, CPagination, CPaginationItem } from '@coreui/react';
import { useSelector } from 'react-redux'

const ScheduleOfDoctors = () => {
  const [message, setMessage] = useState('');
  const [scheduleName, setScheduleName] = useState([]);
  const [doctorsInfo, setDoctorsInfo ] = useState([]);
  const [tableSchedule, setTableSchedule] = useState([]);
  const [params, setParams] = useState({
    schedule_name: 'schedule',
    doctors_name: null,
    limit: 15,
    offset: 0,
    });
  const token = useSelector((state) => state.token);

  const handleScheduleNameChange = (event) => {
    const selectedId = event.target.value; 
    const selectedSchedule = scheduleName.find(schedule => schedule.id === parseInt(selectedId));
    if (selectedSchedule) {
        setParams(prevParams => ({
            ...prevParams,
            schedule_name: selectedSchedule.name, 
        }));
        fetchData(); 
    } else {
        console.error("Расписание с таким ID не найдено.");
    }
  };
  

  const handleDoctorsNameChange = (event) => {
    const selectedId = event.target.value; 
    if (selectedId === '') {
        setParams(prevParams => ({
           ...prevParams,
            doctors_name: null,
        }));
        fetchData(); 
    } else {
        const selectedDoctor = doctorsInfo.find(doctor => doctor.id === parseInt(selectedId));
        if (selectedDoctor) {
            setParams(prevParams => ({
               ...prevParams,
                doctors_name: selectedDoctor.name,
            }));
            setParams(prevParams => ({
              ...prevParams,
               offset: 0,
           }));
            fetchData(); 
        } else {
            console.error("Врач с таким ID не найден.");
        }
    }
};


  const nextPage = () => {
    setParams(prevParams => ({
    ...prevParams,
      offset: prevParams.offset + params.limit,
    }));
    fetchData();
  };


  const previousPage = () => {
    if (params.offset > 0) {
      setParams(prevParams => ({
      ...prevParams,
        offset: prevParams.offset - params.limit,
      }));
      fetchData();
    }
  };


  const fetchScheduleName = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/schedule_name`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
        }
        );
        const data = await response.json();
        setScheduleName(data);
        handleScheduleNameChange(data[0].name);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };

  const fetchDoctorsInfo = async () => {
    try {
        const response = await fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/doctors/doctors_info`,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setDoctorsInfo(data);
    } catch (error) {
        console.error('Ошибка при получении данных:', error);
    }
    };
  
  const fetchData = async () => {
      let url = `${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/schedule/doctors_schedule?`;
      if (params.schedule_name) {
        url += `&schedule_name=${params.schedule_name}`;
      }
      if (params.doctors_name) {
        url += `&doctors_name=${params.doctors_name}`;
      }
      if (params.limit) {
        url += `&limit=${params.limit}`;
      }
      if (params.offset) {
        url += `&offset=${params.offset}`;
      }
      try {
        const response = await fetch(url,
          {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
          }
        );
        const data = await response.json();
        setTableSchedule(data);
      } catch (error) {
        console.error('Ошибка при получении данных:', error);
      }
    };

  useEffect(() => {
      fetchScheduleName()
      fetchDoctorsInfo();
      fetchData();
      }, [params]);

  const columns = [
    { key: 'date', _style: { width: '20%' }, label: 'Дата' },
    { key: 'name', _style: { width: '30%' }, label: 'ФИО' },
    { key: 'modality', _style: { width: '20%' }, label: 'Модальность' },
    { key: 'week', _style: { width: '15%' }, label: 'Неделя' },
    { key: 'weekday', _style: { width: '15%' }, label: 'День недели' },
    { key: 'workhours', _style: { width: '15%' }, label: 'Длительность' },
  ];

  const handleUpload = () => {
    const file = document.getElementById('csvFile').files[0];
    if (!file) {
        setMessage('Файл не выбран');
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    fetch(`${process.env.REACT_APP_SERVER_ADDRESS}/api/v1/doctors/uploadfile/`, {
        method: 'POST',
        body: formData,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
      },
    })
  .then(response => response.json())
  .then(data => {
        setMessage(data.msg || data.detail);
        fetchDoctorsInfo()
    })
  .catch(error => {
        setMessage('Ошибка при загрузке файла', error);
    });
  };


    return (
      <>
        <h1>Расписание по врачам</h1>
        <br></br>
        <CRow>
          <CCol xs={2}>
            <CFormLabel>Название расписания</CFormLabel>
          </CCol>
            <CCol xs={3}>
                <CFormSelect 
                    aria-label="Выберите название расписания"
                    options={[
                      { label: 'Выберите название расписания', value: '' },
                      ...scheduleName.map(item => ({
                    label: item.name,
                    value: item.id.toString(),
                    }))]}
                    onChange={handleScheduleNameChange}
                />
            </CCol>
        </CRow>
        <br></br>
        <CRow>
          <CCol xs={2}>
            <CFormLabel>Врач</CFormLabel>
          </CCol>
          <CCol xs={3}>
            <CFormSelect 
                aria-label="Выберите имя врача"
                options={[
                    { label: 'Все врачи', value: '' },
                  ...doctorsInfo.map(item => ({
                        label: item.name,
                        value: item.id.toString(),
                    }))
                ]}
                onChange={handleDoctorsNameChange}
            />
            </CCol>
        </CRow>
        <br></br>
        <CRow>
          <CCol xs={4}>
            <CForm>
              <CFormLabel htmlFor="csvFile">Выберите CSV файл с данными о врачах</CFormLabel>
              <CFormInput type="file" id="csvFile" accept=".csv"/>
            </CForm>
            {message && <p>{message}</p>}
          </CCol>
          <CCol xs={6}>
            <CButton onClick={handleUpload} color="light" variant="outline" className="mt-3">
              Загрузить
            </CButton>
          </CCol>
          
        </CRow>
        <br></br>
        <CRow>
          <CTable striped>
            <CTableHead>
              <CTableRow>
                {columns.map((column, index) => (
                  <CTableHeaderCell key={index} scope="col">{column.label}</CTableHeaderCell>
                ))}
              </CTableRow>
            </CTableHead>
            <CTableBody>
              {tableSchedule.map((item, index) => (
                <CTableRow key={index}>

                  <CTableDataCell>{item.date}</CTableDataCell>
                  <CTableDataCell>{item.name}</CTableDataCell>
                  <CTableDataCell>{item.modality}</CTableDataCell>
                  <CTableDataCell>{item.week}</CTableDataCell>
                  <CTableDataCell>{item.weekday}</CTableDataCell>
                  <CTableDataCell>{item.workhours}</CTableDataCell>
                </CTableRow>
              ))}
            </CTableBody>
          </CTable>
        </CRow>
          <CPagination align="end" aria-label="Page navigation example">
          <CPaginationItem onClick={previousPage}>Previous</CPaginationItem>
          <CPaginationItem onClick={nextPage}>Next</CPaginationItem>
        </CPagination>
      </>
    )
}

export default ScheduleOfDoctors